package fiuba.dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import fiuba.dao.hibernate.GenericDaoHibernate;
import fiuba.dao.MenuDao;
import fiuba.model.LabelValue;

import fiuba.model.Menu;
import fiuba.model.MenuItem;

 
public class MenuDaoHibernate extends GenericDaoHibernate<Menu, Long> 
    implements MenuDao {	
	
	public MenuDaoHibernate(){
		super(Menu.class);
	}
	
	/**
     * {@inheritDoc}
     */
    public Menu saveMenu(Menu menu) {
        log.debug("menu's id: " + menu.getId());
        menu = super.save(menu);
//        getHibernateTemplate().saveOrUpdate(menu);
        // necessary to throw a DataIntegrityViolation and catch it in MenuManager
        getHibernateTemplate().flush();
        return menu;
    }

    /**
     * Overridden simply to call the saveMenu method. This is happenening 
     * because saveMenu flushes the session and saveObject of BaseDaoHibernate 
     * does not.
     *
     * @param menu the menu to save
     * @return the modified menu (with a primary key set if they're new)
     */
    @Override
    public Menu save(Menu menu) {
        return this.saveMenu(menu);
    }
    
    @SuppressWarnings("unchecked")
    public List<Menu> getMenus(){
    	return getHibernateTemplate().find("from Menu m order by upper(m.name)");
    }

    @SuppressWarnings("unchecked")
    public List<LabelValue> getOtherMenuItems (Menu menu){
  
    	 
    	Session session = this.getSessionFactory().openSession(); 
    	Query query = session.getNamedQuery("menu.menuItemsLeft"); 
    	if (menu.getId() != null){
    	   query.setLong("menuId", menu.getId());
    	}else {
    	   query.setLong("menuId", 0);
    	}
    	List result = query.list(); 
    	if (result == null) { 
    		log.info("Could not retrieve other menuItems."); 
    	} 
    	
    	List<LabelValue> menuItems = new ArrayList<LabelValue>();
	    for (Object item : result) {
	        // convert the user's roles to LabelValue Objects
	        menuItems.add(new LabelValue( ((MenuItem)item).getName(), ((MenuItem)item).getId().toString()));
	    }
    	session.close(); 
    	return menuItems; 
    } 
   

}
